<template>
  <a-modal
      :width="500"
      :visible="visible"
      :title="title"
      @cancel="onClose"
      @ok="onSubmit"
      ok-text="确定"
      :destroyOnClose="true"
      :confirmLoading="loading"
  >
    <a-alert type="warning" style="margin-bottom: 20px" v-if="id">
      <template #description>
        <p>如果更改招商经理，则原招商经理会从原来团队移除。</p>
      </template>
    </a-alert>
    <a-form>
      <a-row :wrap="true" :gutter="12">
        <a-col :span="24">
          <a-form-item label="团队名称" v-bind="validateInfos.name">
            <a-input
                v-model:value="formData.name"
                placeholder="请输入团队名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="招商经理" v-bind="validateInfos.leader_uid">
            <a-row class="user-tag" align="middle">
              <a-tag
                  closable
                  v-for="(user, index) of idList.user"
                  :key="user.uid"
                  @close="idListRemove('user', index, user.uid)"
                  style="margin: 5px 10px 5px 0"
              >
                <a-avatar
                    :src="user.avatar"
                    style="color: #fff; background-color: #2681f3"
                >
                  <template #icon>
                    <UserOutlined/>
                  </template>
                </a-avatar>
                <span class="ml-10"> {{ user.realname }} </span>
              </a-tag>
              <a-button type="primary" ghost @click="chooseMember"
              >选择
              </a-button
              >
            </a-row>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="绑定项目" v-bind="validateInfos.village_id">
            <a-select
                v-model:value="formData.village_id"
                :options="villageOptions"
                placeholder="请选择项目"
                :allowClear="true"
                mode="multiple"
                style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>


    <!-- 选择人员 -->
    <ChooseOrgMember
        :visible="chooseMemberVisible"
        :getDetail="true"
        :deptDisabled="true"
        :uMax="1"
        :selectNoTeam="false"
        @request="$utils.commonRequest"
        @close="closeChooseMemberModal"
        @success="handleMemberSelect"
        :checkedList="idList"
    />
  </a-modal>

</template>
<script>
import {defineComponent, reactive, toRefs, computed, watch} from "vue";
import {Form, message} from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
import {UserOutlined} from "@ant-design/icons-vue";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
import {ChooseOrgMember} from "bl-common-vue3";
import _ from "lodash";

export default defineComponent({
  name: "AddBusinessTeam",
  props: {
    id: {
      type: [Number, String],
      default: 0,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    villageOptions: {
      type: Array,
      default: () => [],
    },
  },
  components: {UserOutlined, ChooseOrgMember},
  setup(props, {emit}) {
    const state = reactive({
      idList: {},
      chooseMemberVisible: false,
      loading: false,
    });

    const formData = reactive({
      village_id: undefined,
      name: '',
      leader_uid: undefined,
    });
    const ruleRef = reactive({
      name: [{required: true, message: "必填"}],
      leader_uid: [{required: true, message: "必选"}],
      village_id: [{required: true, message: "必选"}],
    });

    const title = computed(() => {
      return props.id ? '编辑团队' : '新增团队';
    });

    const {resetFields, validate, validateInfos} = useForm(formData, ruleRef);

    const onSubmit = () => {
      validate().then(() => {
        let params = {};
        for (let key in formData) {
          if (formData[key] || formData[key] === 0) {
            params[key] = formData[key];
          }
        }
        state.loading = true;
        if (props.id) {
          params.id = props.id;
          // 编辑
          request.put("/org", "/business/customerTeam/edit", params).then((res) => {
            message.success(res.msg || "编辑成功!");
            emit("success");
          }).finally(() => {
            state.loading = false;
          });
        } else {
          // 添加
          request.post("/org", "/business/customerTeam/add", params).then((res) => {
            message.success(res.msg || "添加成功!");
            emit("success");
          }).finally(() => {
            state.loading = false;
          });
        }

      });
    };


    const idListRemove = (type = "user", index, uid) => {
      state.idList[type].splice(index, 1);
      formData.leader_uid = undefined;
    };

    const chooseMember = () => {
      state.chooseMemberVisible = true;
    };


    const closeChooseMemberModal = () => {
      state.chooseMemberVisible = false;
    };

    const handleMemberSelect = (data) => {
      state.idList = data;
      closeChooseMemberModal();
      formData.leader_uid = data?.user?.length ? data.user[0].uid : undefined;
    };


    const onClose = () => {
      emit("cancelAdd");
    };


    const setModelRef = (state) => {
      for (let key in state) {
        formData[key] = state[key];
      }
    };

    const getDetail = () => {
      state.loading = true;
      request.get("/org", "/business/customerTeam/teamDetail", {id: props.id}).then((res) => {
        let info = res?.data || {};
        setModelRef({
          name: info?.name,
          village_id: info?.village_id,
          leader_uid: info?.leader_uid,
        })
        state.idList = {
          department: [],
          user: _.isEmpty(info?.execute_info) ? [] : [{...info.execute_info}],
        };
        state.loading = false;
      });
    }

    const init = () => {
      if (!props.id) return;
      getDetail();
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            resetFields();
            state.idList = {};
            state.loading = false;
          }
        }
    );

    return {
      ...toRefs(state),
      formData,
      validateInfos,
      title,
      onClose,
      onSubmit,
      idListRemove,
      chooseMember,
      closeChooseMemberModal,
      handleMemberSelect,
    };
  },
});
</script>

<style lang="less" scoped>
.user-tag :deep(.ant-tag) {
  border-radius: 20px !important;
  padding: 0 12px 0 0 !important;
  background: #f1f1f1;
  border: none;
}

:deep(.ant-alert-description) {
  font-size: 12px;

  p {
    margin-bottom: 6px;

    &:last-of-type {
      margin-bottom: 0;
    }
  }
}

:deep(.ant-alert-with-description.ant-alert-no-icon) {
  padding: 6px 10px;
}
</style>
